# -*- coding: utf-8 -*-

from math import ceil


class Pagination(object):
    page = 0
    per_page = 20
    total_count = 0

    def __init__(self, obj, page, per_page=20):
        self.page = page
        self.per_page = per_page
        self.total_count = obj.count()
        self.pager = obj.paginate(
            page,
            per_page=per_page,
            error_out=False)
        self.data = self.pager.items

    @property
    def pages(self):
        return int(ceil(self.total_count / float(self.per_page)))

    @property
    def has_prev(self):
        return self.page > 1

    @property
    def has_next(self):
        return self.page < self.pages

    @property
    def begin(self):
        count = self.page * self.per_page
        if len(self.data) != 1:
            count -= 1
        return count

    @property
    def end(self):
        return self.begin + len(self.data) - 1

    def iter_pages(self, left_edge=2, left_current=2,
                   right_current=5, right_edge=2):
        last = 0
        for num in xrange(1, self.pages + 1):
            if num <= left_edge or \
               (num > self.page - left_current - 1 and \
                num < self.page + right_current) or \
               num > self.pages - right_edge:
                if last + 1 != num:
                    yield None
                yield num
                last = num
